package net.sxnic.item.mdata.action;

import java.util.Date;
import java.util.List;

import net.sxnic.item.mdata.Mdata;
import net.sxnic.ugr.context.AppContext;
import net.sxnic.ugr.user.User;
import net.sxnic.workflow.task.Task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 撤销
 * @author 孙宇飞
 *
 */
@SuppressWarnings("serial")
public class Withdraw extends MdataAction{

	private Logger logger = LoggerFactory.getLogger(Withdraw.class);
	
	public String execute() throws Exception{
		
		String redirectUrl="";
		User user = ucenterService.findUserByUserName(AppContext.getUserName(request));
		String assigee = "";
		if(ucenterService.isUserInRole(user, "approver")){
			assigee = user.getUsername();
			redirectUrl="success";
		}else {
			assigee = ucenterService.findTaskAssignee(user);
			redirectUrl="verify_list";
		}	
		
		//只有自己才能删除
		Task task = taskManager.get(taskId);		
		if(!task.getAssignee().equals(assigee)){
			msg ="maindata.withdrawNoAuthError";
			logger.info(AppContext.getUserName(request)+"=====非任务承担者试图删除相关实体！====="+task.getId());
			return redirectUrl;
		}
		
		//只有当前任务结束时才能撤销	
		if(task.isEnded()){
			//只有后续任务没有结束才能撤销
			//第一个任务没有fromTask
			List<Task> list = taskManager.findBy("fromTask", task);			
			boolean canCancel = true;
			if(list==null||list.size()==0){
				canCancel = true;
			}else{				
				for(Task t:list){
					if(t.isEnded()){
						canCancel = false;
						break;
					}
				}
			}
			
			if(!canCancel){
				//后续任务已完成，不能撤销
				msg="maindata.withdrawNextTaskHashEndedError";
				return redirectUrl;
			}
			
			if (canCancel) {
				// BeanUtils.copyProperties(temp, task);
				task.setOutcomeOperator(user.getUsername());
				task.setOutcomeOperateDate(new Date());
				// task.setCreationDate(new Date()); // 重新设置创建时间
				task.setEndDate(null);
				task.setStatus(Task.TASK_STATUS_ACTIVE);
				task.setOutcomeOperateReason("");
				taskManager.update(task);
				

				for (Task t : list) {
					t.setStatus(Task.TASK_STATUS_CANCELED);
					// TODO 原因
					t.setOutcomeOperateReason("");
					t.setOutcomeOperator(task.getAssignee());
					t.setOutcomeOperateDate(new Date());
					taskManager.update(t);					
				}			
			}
			
			//修改主表状态
			Mdata md = task.getMdata();
			md.setStatus(task.getNode().getStatusName());
			md.setStatusOrder(task.getNode().getStatusCode());
			mdManager.update(md);
			
			logger.debug("用户:{} 撤销:{} 成功！",user.getUsername(),task);
			
			msg ="withdrawSuccess";
		}else{
			//项目未提交，不能撤销
			msg ="maindata.withdrawNoSubmit";
			logger.info(user.getUsername()+"=====任务撤销失败！====="+task.getId());
			return redirectUrl;
		}
		
		return redirectUrl;
	}
	
}